package com.fin.zw.intelligentbot.service;


import com.fin.zw.intelligentbot.entity.*;
import com.fin.zw.intelligentbot.enums.SourceType;
import com.fin.zw.intelligentbot.model.request.CircuitRequest;
import com.fin.zw.intelligentbot.model.session.SessionModel;
import com.fin.zw.intelligentbot.repository.LineInfoRepository;
import com.fin.zw.intelligentbot.repository.RobotInfoRepository;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.collections4.IterableUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Service("circuitService")
public class LineInfoService {

    private static final Logger log = LoggerFactory.getLogger(LineInfoService.class);

    @Autowired
    private LineInfoRepository lineInfoRepository;

    @Autowired
    private RobotInfoRepository robotInfoRepository;

    @Autowired
    private CommonService commonService;

    /**
     * 分页查询对应线路
     * @param pageable
     * @param request
     * @param sessionModel
     * @return
     */
    public Page<LineInfo> querySceneInfoAll(Pageable pageable,
                                            CircuitRequest request,
                                            SessionModel sessionModel){
        BooleanBuilder builder = new BooleanBuilder();
        QLineInfo qLineInfo = QLineInfo.lineInfo;
        if(sessionModel.getCompanyId() != null){
            builder.and(qLineInfo.companies.contains(commonService.getCompany(sessionModel)));
        }else{ //超级管理方
            builder.and(qLineInfo.source.eq(SourceType.SAFEMANAGER));
        }
        if(request.getName() != null){
            builder.and(qLineInfo.name.eq(request.getName()));
        }
        if(request.getCode() != null){
            builder.and(qLineInfo.code.eq(request.getCode()));
        }
        Page<LineInfo> page = lineInfoRepository.findAll(builder,pageable);
        return page;
    }

    /**
     * 查询线路（主要使用在配置机器人）
     * @param sessionModel
     * @return
     */
    public List<LineInfo> getCircuitList(SessionModel sessionModel){
        BooleanBuilder builder = new BooleanBuilder();
        QLineInfo qLineInfo = QLineInfo.lineInfo;
        if(sessionModel.getCompanyId() != null){
            builder.and(qLineInfo.companies.contains(commonService.getCompany(sessionModel)));
        }else{ //超级管理方
            builder.and(qLineInfo.source.eq(SourceType.SAFEMANAGER));
        }
        Iterable<LineInfo> iterable = lineInfoRepository.findAll(builder);
        List<LineInfo> list = IterableUtils.toList(iterable);
        return list;
    }

    /**
     * 线路创建
     * @param request
     * @param sessionModel
     */
    public void createCircuit(CircuitRequest request,
                              SessionModel sessionModel){
        LineInfo circuit = new LineInfo();
        BeanUtils.copyProperties(request,circuit);
        Set<Company> set = commonService.getCompanySet(sessionModel,request.getCompanyIds());
        if(sessionModel.getCompanyId() == null){
            circuit.setSource(SourceType.SAFEMANAGER);//管理端
        }else{
            circuit.setSource(SourceType.COMPANY);//企业
        }
        circuit.setCompanies(set);
        lineInfoRepository.save(circuit);
    }

    /**
     * 线路更新
     * @param request
     * @param sessionModel
     */
    public void updateCircuit(CircuitRequest request,
                              SessionModel sessionModel){
        Optional<LineInfo> optional = lineInfoRepository.findById(request.getId());
        if(!optional.isPresent()){
            log.info("更新的数据不存在");
            throw new RuntimeException("更新的数据不存在");
        }
        LineInfo circuit = optional.get();
        Set<Company> set = commonService.getCompanySet(sessionModel,request.getCompanyIds());

        BeanUtils.copyProperties(request, circuit);
        circuit.setCompanies(set);
        lineInfoRepository.save(circuit);
    }

    /**
     * 线路删除
     * @param id
     * @param sessionModel
     */
    public void deleteCircuit(String id,SessionModel sessionModel){
        Optional<LineInfo> optional = lineInfoRepository.findById(id);
        if(!optional.isPresent()){
            log.info("更新的数据不存在");
            throw new RuntimeException("更新的数据不存在");
        }
        LineInfo circuit = optional.get();
        String error = commonService.exitSource(sessionModel,circuit.getSource());
        if(error != null){
            log.info(error);
            throw new RuntimeException(error);
        }
        //需要判断在机器人中是否绑定
        Iterator<RobotInfo> infoIterator = robotInfoRepository.findAll(QRobotInfo.robotInfo.gateway.id.eq(id)).iterator();
        if(infoIterator.hasNext()){
            log.info("该线路已经绑定机器人，请先解除绑定");
            throw new RuntimeException("该线路已经绑定机器人，请先解除绑定");
        }
        lineInfoRepository.delete(circuit);
    }

}
